<!--
 * @Description: 
 * @Author: Gaq
 * @Date: 2022-11-09 12:05:13
 * @LastEditTime: 2022-11-13 22:19:51
 * @LastEditors: Gaq
-->
<script setup>
import { regionData, CodeToText, TextToCode } from "element-china-area-data";
import request from "@/utils/request";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";

const { state, commit, dispatch } = useStore();
let userId = computed(() => state.userId);
let dialogShow = computed(() => state.dialogFormVisible);
let dialogFormVisible = ref(dialogShow.value);

let addObj = reactive({
  userId: userId.value,
  name: "",
  phoneNumber: "",
  region: "",
  detail: "",
  isDefault: 0,
});
const formRef = ref();
const valTel = (rule, str, callback) => {
  let regExp = /^[1][3,4,5,7,8][0-9]{9}$/;
  if (regExp.test(str)) {
    return callback();
  }
  callback(new Error("请输入合法的手机号"));
};
const rules = reactive({
  name: [
    { required: true, max: 25, message: "长度不超过25个字符", trigger: "blur" },
  ],
  region: [{ required: true, message: "地址信息不能为空" }],
  detail: [
    {
      required: true,
      min: 5,
      max: 120,
      message: "详细地址长度需要是5-120个汉字或字符",
      trigger: "blur",
    },
  ],
  phoneNumber: [{ required: true, validator: valTel, trigger: "blur" }],
});

const getAddressList = (value) => {
  dispatch("getAddressList", value);
};

let props = defineProps({
  itemId: Number,
});
onBeforeMount(() => {
  getAddressList(userId.value);
  if (props.itemId) {
    defaultAddress(props.itemId);
  }
});
const defaultAddress = (value) => {
  request.get(`/address/getOne/${value}`).then((res) => {
    addObj.name = res.data.name;
    addObj.phoneNumber = res.data.phoneNumber;
    addObj.detail = res.data.detail;
    addObj.isDefault = res.data.isDefault;
    addObj.region = getCityCode(res.data.region);
  });
};
watch(props, (newVal) => {
  defaultAddress(newVal.itemId);
});

const addressChange = (arr) => {
  return (
    CodeToText[arr[0]] + "/" + CodeToText[arr[1]] + "/" + CodeToText[arr[2]]
  );
};

const getCityCode = (cityText) => {
  var codeArray = [];
  if (cityText != "") {
    var cityArray = cityText.trim().split("/");

    if (cityArray.length == 1) {
      codeArray.push(TextToCode[cityArray[0]].code);
    } else if (cityArray.length == 2) {
      codeArray.push(TextToCode[cityArray[0]].code);
      codeArray.push(TextToCode[cityArray[0]][cityArray[1]].code);
    } else if (cityArray.length == 3) {
      codeArray.push(TextToCode[cityArray[0]].code);
      codeArray.push(TextToCode[cityArray[0]][cityArray[1]].code);
      codeArray.push(TextToCode[cityArray[0]][cityArray[1]][cityArray[2]].code);
    }
  }
  return codeArray;
};

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid && !props.itemId) {
      addObj.region = addressChange(addObj.region);
      console.log(props.itemId);
      // 如果新添加的地址为默认地址，则筛选数据库中已有的地址信息找出isDefault == 1 的
      if (addObj.isDefault == 1) {
        request.get(`/address/getPart/${userId.value}`).then((res) => {
          res.data.map((item) => {
            if (item.isDefault == 1) {
              item.isDefault = 0;
              request.put("/address/updateOne", item);
            }
          });
          // 简单赋值，跳过action直接commit
          commit("GET_ADDRESS_TABLE", res.data);
        });
      }
      request.post("/address/insertOne", addObj).then((res) => {
        if (res.code == 0) {
          ElMessage.success("保存成功");
          getAddressList(userId.value);
          resetForm(formRef.value);
        }
      });
    }
    props.itemId
      ? updateAddress(formEl, props.itemId, addObj)
      : ElMessage.warning("保存失败，请重新填写");
  });
};

const updateAddress = async (formEl, id, value) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      value.region = addressChange(value.region);
      value.addressId = id;
      if (value.isDefault == 1) {
        request.get(`/address/getPart/${userId.value}`).then((res) => {
          res.data.map((item) => {
            if (item.isDefault == 1 && item.addressId !== id) {
              item.isDefault = 0;
              request.put("/address/updateOne", item);
            }
          });
        });
      }
      request.put("/address/updateOne", value).then((res) => {
        if (res.code == 0) {
          ElMessage.success("保存成功");
          defaultAddress(id);
          request.get(`/address/getPart/${state.userId}`).then((res) => {
            commit("GET_ADDRESS_LIST", res.data);
          });
          commit("SET_DIALOG", false);
        }
      });
    } else {
      ElMessage.warning("保存失败，请重新填写");
    }
  });
};
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<template>
  <div>
    <el-form :model="addObj" label-width="100px" :rules="rules" ref="formRef">
      <el-form-item label="收货人姓名" prop="name">
        <el-input v-model="addObj.name" placeholder="请填写收货人姓名" />
      </el-form-item>
      <el-form-item label="地址信息" prop="region">
        <el-cascader
          placeholder="请选择省/市/区"
          :options="regionData"
          v-model="addObj.region"
          @change="addressChange"
        ></el-cascader
      ></el-form-item>
      <el-form-item label="详细地址" prop="detail"
        ><el-input
          v-model="addObj.detail"
          placeholder="请输入详细地址信息，如道路、门牌号、小区楼栋号、单元等信息"
      /></el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber"
        ><el-input v-model="addObj.phoneNumber" placeholder="请填写手机号码"
      /></el-form-item>
      <el-form-item prop="isDefault"
        ><el-checkbox
          label="设置为默认收货地址"
          name="isDefault"
          :true-label="1"
          :false-label="0"
          v-model="addObj.isDefault"
      /></el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)" plain
          >保存</el-button
        >
        <el-button @click="resetForm(formRef)">清空</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
</style>
